package models

import (
	"activity_srv/basic/config"
	"gorm.io/gorm"
	"time"
)

// 拼团表
type GroupBuying struct {
	Id             uint64         `gorm:"column:id;type:bigint UNSIGNED;comment:主键;primaryKey;not null;" json:"id"`                                 // 主键
	UserId         uint64         `gorm:"column:user_id;type:bigint UNSIGNED;comment:用户ID;not null;" json:"user_id"`                                // 用户ID
	TotalNum       uint64         `gorm:"column:total_num;type:bigint UNSIGNED;comment:购买商品数量;not null;" json:"total_num"`                          // 购买商品数量
	GroupNum       string         `gorm:"column:group_num;type:varchar(255);comment:拼团订单号;not null;" json:"group_num"`                              // 拼团订单号
	PersonGroupNum string         `gorm:"column:person_group_num;type:varchar(255);comment:个人订单号;not null;" json:"person_group_num"`                // 个人订单号
	TotalPrice     float64        `gorm:"column:total_price;type:decimal(10, 2) UNSIGNED;comment:购买商品金额;not null;" json:"total_price"`              // 购买商品金额
	GroupGid       uint64         `gorm:"column:group_gid;type:bigint UNSIGNED;comment:拼团商品ID;not null;" json:"group_gid"`                          // 拼团商品ID
	People         uint64         `gorm:"column:people;type:bigint UNSIGNED;comment:拼团人数;not null;" json:"people"`                                  // 拼团人数
	Price          float64        `gorm:"column:price;type:decimal(10, 2) UNSIGNED;comment:单价;not null;" json:"price"`                              // 单价
	StartTime      string         `gorm:"column:start_time;type:datetime(3);comment:开始时间;not null;" json:"start_time"`                              // 开始时间
	EndTime        string         `gorm:"column:end_time;type:datetime(3);comment:结束时间;not null;" json:"end_time"`                                  // 结束时间
	KId            uint64         `gorm:"column:k_id;type:bigint UNSIGNED;comment:团长ID 0为团长;not null;" json:"k_id"`                                 // 团长ID 0为团长
	Status         uint8          `gorm:"column:status;type:tinyint UNSIGNED;comment:状态 1进行中 2已完成 3未完成;not null;" json:"status"`                    // 状态 1进行中 2已完成 3未完成
	InviteCode     string         `gorm:"column:invite_code;type:varchar(255);comment:邀请码;not null;" json:"invite_code"`                            // 邀请码
	GroupType      uint8          `gorm:"column:group_type;type:tinyint UNSIGNED;comment:拼团类型 0普通 1超级;not null;default:0;" json:"group_type"`       // 拼团类型 0普通 1超级
	CreatedAt      time.Time      `gorm:"column:created_at;type:datetime(3);comment:创建时间;not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"` // 创建时间
	UpdatedAt      time.Time      `gorm:"column:updated_at;type:datetime(3);comment:修改时间;not null;default:CURRENT_TIMESTAMP(3);" json:"updated_at"` // 修改时间
	DeletedAt      gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);comment:删除时间;default:NULL;" json:"deleted_at"`                          // 删除时间
}

func (g *GroupBuying) TableName() string {
	return "group_buying"
}

// 创建拼团
func (g *GroupBuying) CreateGroupBuying() error {
	return config.DB.Create(&g).Error
}

func (g *GroupBuying) GetGroupRetail() error {
	return config.DB.Where("id = ?", g.Id).First(&g).Error
}

// 查询用户参与的拼团记录
func (g *GroupBuying) GetGroup(page, pageSize int64) error {
	return config.DB.Where("user_id = ?", g.UserId).Scopes(GetGroupPaginate(page, pageSize)).Find(&g).Error
}
func GetGroupPaginate(page, pageSize int64) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(int(offset)).Limit(int(pageSize))
	}
}

// GetUserGroupRecordsTotal 获取用户拼团记录总数
func (g *GroupBuying) GetUserGroupRecordsTotal() (int64, error) {
	var total int64
	err := config.DB.Where("user_id = ?", g.UserId).Count(&total).Error
	return total, err
}

// 更新邀请码
func (g *GroupBuying) UpdateByInviteCode(actualInviteCode string) error {
	// 更新邀请码
	return config.DB.Where("id = ?", g.Id).Update("invite_code", actualInviteCode).Error
}

// 验证拼团是否存在且有效
func (g *GroupBuying) GetGroupNumById() error {
	return config.DB.Where("group_num = ? AND status = 1", g.GroupNum).First(&g).Error
}

// GetGroupCount 获取拼团人数
func (g *GroupBuying) GetGroupCount(count int64) error {
	return config.DB.Where("group_num = ?", g.GroupNum).Count(&count).Error
}

// GetGroupPByUserId 检查用户是否已经在拼团中
func (g *GroupBuying) GetGroupPByUserId(count int64) error {
	return config.DB.Where("user_id = ? AND group_num = ?", g.UserId, g.GroupNum).Count(&count).Error
}

// GetGroupPGById 获取拼团商品信息
func (g *GroupBuying) GetGroupPGById() error {
	var groupPGoods GroupPGoods
	groupPGoods.Id = g.GroupGid
	return config.DB.Where("id = ?", g.GroupGid).First(&groupPGoods).Error
}

// GetGroupByPeople 获取拼团人数（用于检查是否达到拼团人数）
func (g *GroupBuying) GetGroupByPeople(count int64) error {
	return config.DB.Where("group_num = ?", g.GroupNum).Count(&count).Error
}

// GetUserActiveGroupsCount 获取用户作为团长进行中的拼团数量
func (g *GroupBuying) GetUserActiveGroupsCount() (int64, error) {
	var count int64
	err := config.DB.Where("user_id = ? AND k_id = 0 AND status = 1", g.UserId).Count(&count).Error
	return count, err
}

// GetUserActiveGroupsCountWithTx 在事务中获取用户作为团长进行中的拼团数量
func GetUserActiveGroupsCountWithTx(tx *gorm.DB, userId uint64) (int64, error) {
	var count int64
	err := tx.Where("user_id = ? AND k_id = 0 AND status = 1", userId).Count(&count).Error
	return count, err
}
func (g *GroupBuying) GetGroupById() error {
	return config.DB.Where("id = ?", g.Id).First(&g).Error
}
func (g *GroupBuying) GetUserANdGroupGid() error {
	var count int64
	return config.DB.Where("user_id = ? AND group_gid = ?", g.UserId, g.GroupGid).Count(&count).Error
}

// UpdateGroupStatus 更新拼团状态
func (g *GroupBuying) UpdateGroupStatus(groupNum string, status int64) error {
	return config.DB.Where("group_num = ?", groupNum).Update("status", status).Error
}

// GetGroupByGroupNum 根据拼团编号获取拼团信息
func (g *GroupBuying) GetGroupByGroupNum(groupNum string) error {
	return config.DB.Where("group_num = ?", groupNum).First(&g).Error
}
